package com.dkm.service.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dkm.entity.Message;
import com.dkm.entity.MessagePojo;
import com.dkm.entity.Users;
import com.dkm.mapper.MessagePojoMapper;
import com.dkm.service.MessagePojoService;
import com.dkm.util.ResultUtil;
import com.dkm.websocket.CommunicateWebSocket;

@Service
public class MessagePojoServiceImpl implements MessagePojoService {

	//注入消息持久层
	@Autowired
	private MessagePojoMapper messagePojoMapper;
	//注入websocket
	@Autowired
	private CommunicateWebSocket communicateWebSocket;
	
	@Override
	public ResultUtil addMessage(String sender_id,String content,String receiver_id) {
		//创建消息对象
		MessagePojo message=new MessagePojo();
		
		if(sender_id==null&&sender_id=="") {
			return new ResultUtil(-1, "发送失败！发送人数据异常", null);
		}
		message.setSender_id(sender_id);
		
		//设置消息内容
		message.setContent(content);
		//发送时间
		message.setSendTime(new Date());
		//消息状态
		message.setStatus("未读");
		
		//接收人存在
		if(!"0".equals(receiver_id)) {
//			if(receiver_id==null&&receiver_id=="") {
//				return new ResultUtil(-1, "发送失败！接收人不存在", null);
//			}
			//设置接收人
			message.setReceiver_id(receiver_id);
			//消息类型
			message.setMtype("普通消息");
			
			//content=sender_id+"|"+content+"|"+receiver_id;
			//发给指定用户
			//communicateWebSocket.sendToUser(message);
		}else {
			message.setMtype("广播消息");
			//设置接收人为空
			message.setReceiver_id(null);
			//content=sender_id+"|"+content;
			//发给所有用户（广播）
			//communicateWebSocket.sendAll(message);
		}
		
		//添加消息
		int r=messagePojoMapper.addMessage(message);
		if(r>0) {
			//添加成功获取自增id
			Integer mid=message.getMid();
			System.out.println("mid>"+mid);
			//根据插入消息id获取消息信息
			MessagePojo message1=messagePojoMapper.getMessageByMid(mid);
			
			System.out.println("message>"+message1);
			
			if(!"0".equals(receiver_id)) {
				//发给指定用户
				communicateWebSocket.sendToUser(message1);
			}else {
				//发给所有用户（广播）
				communicateWebSocket.sendAll(message1);
			}
			
			return new ResultUtil(0, "发送成功！", message);
		}
		return new ResultUtil(-1, "发送失败！", null);
	}

}
